<?php

namespace app\admin\controller;

use app\admin\logic\GoodsLogic;
use think\facade\Db;
use think\facade\Cache;
use think\facade\View;

class System extends Base
{
    /*
     * 配置入口
     */
    public function index()
    {
        /*配置列表*/
        $group_list = [
            'basic' => ['name'=>'基础设置','url'=>url('System/index',['inc_type'=> 'basic']),'inc_type'=>'basic'],
            'shop' => ['name'=>'商城设置','url'=>url('System/index',['inc_type'=> 'shop']),'inc_type'=>'shop'],
            'reg' => ['name'=>'登录注册','url'=>url('System/index',['inc_type'=> 'reg']),'inc_type'=>'reg'],
            'xieyi' => ['name'=>'注册协议','url'=>url('System/index',['inc_type'=> 'xieyi']),'inc_type'=>'xieyi'],
//            'bonus' => ['name'=>'奖金设置','url'=>url('System/index',['inc_type'=> 'bonus']),'inc_type'=>'bonus'],
//            'sms' => ['name'=>'短信设置','url'=>U('System/index',['inc_type'=> 'sms'])],
           // 'express' => ['name'=>'物流设置','url'=>U('System/index',['inc_type'=> 'express'])],
        ];

        //选出开放配置的插件
//        $plugin = Db::name('Plugin')->where(['status'=>1,'userset'=>1])->select();
//        if($plugin){
//            foreach($plugin as $plug){
//                $group_list[$plug['type']."__".$plug['code']] =  ['name'=>$plug['name'],'url'=>U('Plugin/setting',array('type'=>$plug['type'],'code'=>$plug['code']))];
//            }
//        }

        View::assign('group_list', $group_list);
        $inc_type = input('get.inc_type', 'basic');
        View::assign('inc_type', $inc_type);
        $config = tpCache($inc_type);

        View::assign('config', $config);//当前配置项


        View::assign('wallet',logic('Wallet')->getName());

        $platform = config('extra_platform');
        View::assign('platform',$platform);
        //会员级别
        $level = Db::name('user_level')->select();
        //管理级别
        $level1 = Db::name('user_level1')->select();
        View::assign('level_arr',$level);
        View::assign('level1_arr',$level1);

        $cur_date = date('Y-m-d',getCurTime());
        View::assign("cur_date",$cur_date);
        $domain = getCurUrl();
        $show_test = 0;
        if(strpos($domain,'aqwq')!==false || strpos($domain,'yhr') !==false){
            $show_test = 1;
        }
        View::assign('show_test',$show_test);
        return View::fetch($inc_type);
    }

    /*
     * 新增修改配置
     */
    public function handle()
    {
        $platform = config('platform');
        View::assign('platform',$platform);
        $param = input('post.');
        $inc_type = input('inc_type');
        if($inc_type=='xieyi'){
            $param['xieyi_content'] = htmlspecialchars_decode($param['xieyi_content']);
            $param['yinsi_content'] = htmlspecialchars_decode($param['yinsi_content']);
            $param['supply_xieyi_content'] = htmlspecialchars_decode($param['supply_xieyi_content']);
        }
        if($inc_type=='reg'){
            foreach($platform as $pl=>$pl_name){
                $param['reg_'.$pl] = $param['reg_'.$pl]??0;
                $param['mobile_login_'.$pl] = $param['mobile_login_'.$pl]??0;
                $param['auth_login_'.$pl] = $param['auth_login_'.$pl]??0;
                $param['login_mast_'.$pl] = $param['login_mast_'.$pl]??0;
            }

        }
        if(!empty($param['store_logo'])){
            $this->createIco($param['store_logo']);
        }
        tpCache($inc_type, $param);
        return json(['status'=>1,'msg'=>'保存成功']);
        $this->success("操作成功", U('System/index', array('inc_type' => $inc_type)));
    }


    /**
     * 清空系统缓存
     */
    public function cleanCache()
    {
        delFile(RUNTIME_PATH);
        Cache::clear();
        $quick = input('quick', 0);
        if ($quick == 1) {
            $this->success('清除成功');
        } else {
            $script = "<script>parent.layer.msg('缓存清除成功', {time:3000,icon: 1});window.location='/index.php?m=admin&c=Index&a=welcome';</script>";
        }
        exit($script);
    }

    //发送测试邮件
    public function send_email()
    {
        $param = I('post.');
        $res = send_email($param['test_eamil'], '后台测试', '测试发送验证码:' . mt_rand(1000, 9999));
        exit(json_encode($res));
    }

    public function createIco($logo=''){
        // 生成ico图标
        $image = imagecreatefromstring(file_get_contents($logo));
        $filename = 'favicon.ico';
        $sizes = array(16, 32, 48);
        
        // 准备ICO文件头部
        $iconData = pack('vvv', 0, 1, count($sizes)); // 0=保留, 1=ICO类型, count($sizes)=图像数量
        
        // 收集所有图像数据以便后续处理
        $imageDataArray = [];
        
        // 计算头部大小: 6字节(文件头) + 16字节(每个图像目录)
        $offset = 6 + 16 * count($sizes);
        
        // 为每个尺寸创建图像并收集数据
        foreach($sizes as $size) {
            // 创建指定尺寸的图像
            $resized = imagecreatetruecolor($size, $size);
            
            // 设置透明度支持
            imagealphablending($resized, false);
            imagesavealpha($resized, true);
            
            // 调整大小并保持透明度
            imagecopyresampled($resized, $image, 0, 0, 0, 0, $size, $size, imagesx($image), imagesy($image));
            
            // 捕获PNG数据
            ob_start();
            imagepng($resized);
            $pngData = ob_get_contents();
            ob_end_clean();
            
            // 存储图像数据
            $imageDataArray[] = [
                'size' => $size,
                'data' => $pngData,
                'offset' => $offset
            ];
            
            // 更新下一个图像的偏移量
            $offset += strlen($pngData);
            
            // 释放资源
            imagedestroy($resized);
        }
        
        // 构建ICO文件目录结构
        foreach($imageDataArray as $imgData) {
            $size = $imgData['size'];
            $data = $imgData['data'];
            
            // 添加图像目录条目
            $iconData .= 
                chr($size) .                // 宽度
                chr($size) .                // 高度
                chr(0) .                    // 调色板颜色数 (0表示无调色板或>=256色)
                chr(0) .                    // 保留 (必须为0)
                pack('v', 1) .              // 颜色平面数 (对ICO必须为1)
                pack('v', 32) .             // 每像素位数 (32=RGBA)
                pack('V', strlen($data)) .  // 图像数据大小
                pack('V', $imgData['offset']); // 图像数据偏移量
        }
        
        // 添加所有图像数据
        foreach($imageDataArray as $imgData) {
            $iconData .= $imgData['data'];
        }
        
        // 写入文件
        file_put_contents(public_path() . $filename, $iconData);
        imagedestroy($image);
        return public_path() . $filename;
    }

}